package priv.mill.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import priv.mill.controller.util.RetenObj;
import priv.mill.entry.Power;
import priv.mill.server.PowerService;

@Controller
@RequestMapping("Power")
public class PowerController {

	@Autowired
	private PowerService powerService;

	private static final Logger logger = Logger.getLogger(PowerController.class);

	@RequestMapping("getPowerById")
	@ResponseBody
	public RetenObj getPowerById(@RequestParam("PowerId") Integer powerId) {
		try {
			return warpData(powerService.getPowerById(powerId), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	private RetenObj warpData(Object object, int i) {
		RetenObj retenObj = new RetenObj();
		retenObj.setData(object);
		retenObj.setStatus(i);
		return retenObj;
	}

	@RequestMapping("getPowerByEntry")
	@ResponseBody
	public RetenObj getPowerByEntry(Power power) {
		try {
			return warpData(powerService.getPowerByEntry(power), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("getPowersByPage")
	@ResponseBody
	public RetenObj getPowersByPage(Power power) {
		try {
			return warpData(powerService.getPowersByPage(power), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("updatePower")
	@ResponseBody
	public RetenObj updatePower(Power power) {
		try {
			int result = powerService.updatePower(power);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}
	

	@RequestMapping("insertPower")
	@ResponseBody
	public RetenObj insertPower(Power power) {
		try {
			int result = powerService.insertPower(power);
			if (result > 0)
				return warpData(power.getPowerId(), 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("deletePower")
	
	@ResponseBody
	public RetenObj deletePower(Integer powerId) {
		try {
			int result = powerService.deletePower(powerId);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}

	}
}
